//
//  MainViewController.swift
//  Webo10
//
//  Created by ChengXiwu on 2017/7/28.
//  Copyright © 2017年 ChengXiwu. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    // MARK: - 监听方法
    @objc fileprivate func clickComposedButton(){
        logPrint("点击了撰写按钮")
    }

    // MARK: - 视图生命周期方法
    override func viewDidLoad() {
        super.viewDidLoad()
        // 添加控制器并不会创建tabBar中的按钮,懒加载是无处不在的
        addChildViewControllers()
        // 设置撰写按钮
        setupComposedButton()
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        // 会创建tabBar中所有控制器对应的按钮
        super.viewWillAppear(animated)
        // 将撰写按钮弄到前面
        tabBar.bringSubview(toFront: composeButton)
    }
    
    // MARK: - 懒加载控件
    fileprivate lazy var composeButton: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")
    
}


// MARK: - 设置界面
extension MainViewController{
    
    fileprivate func setupComposedButton(){
        // 添加按钮
        tabBar.addSubview(composeButton)
        
        let count = childViewControllers.count
        // 让按钮宽一点点,能够解决手指触摸的容错问题
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composeButton.frame = tabBar.bounds.insetBy(dx: w * 2, dy: 0)
        
        // 添加监听方法
        composeButton.addTarget(self, action: #selector(clickComposedButton), for: UIControlEvents.touchUpInside)
    }
    
    fileprivate func addChildViewControllers() {
        addChildViewController(vc: HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(vc: MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(vc: DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(vc: ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    fileprivate func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        // 设置标题
        vc.title = title
        // 设置图像
        vc.tabBarItem.image = UIImage(named: imageName)
        // 导航控制器
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }

}
